package services

import (
	"fmt"
	"jianianhua-server/database"
	"jianianhua-server/models"
)

// CreateBannerRequest 创建轮播图请求
type CreateBannerRequest struct {
	Title     string `json:"title" binding:"required"`
	ImageURL  string `json:"image_url" binding:"required"`
	LinkURL   string `json:"link_url"`
	SortOrder int    `json:"sort_order"`
	Status    int    `json:"status"`
}

// UpdateBannerRequest 更新轮播图请求
type UpdateBannerRequest struct {
	Title     string `json:"title"`
	ImageURL  string `json:"image_url"`
	LinkURL   string `json:"link_url"`
	SortOrder int    `json:"sort_order"`
	Status    int    `json:"status"`
}

// BannerService 轮播图服务
type BannerService struct{}

// NewBannerService 创建轮播图服务
func NewBannerService() *BannerService {
	return &BannerService{}
}

// CreateBanner 创建轮播图
func (s *BannerService) CreateBanner(req *CreateBannerRequest) (*models.Banner, error) {
	banner := &models.Banner{
		Title:     req.Title,
		ImageURL:  req.ImageURL,
		LinkURL:   req.LinkURL,
		SortOrder: req.SortOrder,
		Status:    req.Status,
	}

	if banner.Status == 0 {
		banner.Status = 1 // 默认启用
	}

	err := database.DB.Create(banner).Error
	if err != nil {
		return nil, fmt.Errorf("创建轮播图失败: %v", err)
	}

	return banner, nil
}

// GetBanners 获取轮播图列表
func (s *BannerService) GetBanners() ([]models.Banner, error) {
	var banners []models.Banner
	err := database.DB.Where("status = ?", 1).Order("sort_order ASC, created_at DESC").Find(&banners).Error
	if err != nil {
		return nil, fmt.Errorf("获取轮播图列表失败: %v", err)
	}

	return banners, nil
}

// GetBanner 获取轮播图详情
func (s *BannerService) GetBanner(id uint) (*models.Banner, error) {
	var banner models.Banner
	err := database.DB.Where("id = ?", id).First(&banner).Error
	if err != nil {
		return nil, fmt.Errorf("轮播图不存在")
	}

	return &banner, nil
}

// UpdateBanner 更新轮播图
func (s *BannerService) UpdateBanner(id uint, req *UpdateBannerRequest) (*models.Banner, error) {
	var banner models.Banner
	err := database.DB.Where("id = ?", id).First(&banner).Error
	if err != nil {
		return nil, fmt.Errorf("轮播图不存在")
	}

	// 更新字段
	if req.Title != "" {
		banner.Title = req.Title
	}
	if req.ImageURL != "" {
		banner.ImageURL = req.ImageURL
	}
	if req.LinkURL != "" {
		banner.LinkURL = req.LinkURL
	}
	if req.SortOrder >= 0 {
		banner.SortOrder = req.SortOrder
	}
	if req.Status >= 0 {
		banner.Status = req.Status
	}

	err = database.DB.Save(&banner).Error
	if err != nil {
		return nil, fmt.Errorf("更新轮播图失败: %v", err)
	}

	return &banner, nil
}

// DeleteBanner 删除轮播图
func (s *BannerService) DeleteBanner(id uint) error {
	var banner models.Banner
	err := database.DB.Where("id = ?", id).First(&banner).Error
	if err != nil {
		return fmt.Errorf("轮播图不存在")
	}

	err = database.DB.Delete(&banner).Error
	if err != nil {
		return fmt.Errorf("删除轮播图失败: %v", err)
	}

	return nil
}
